package com.xdl.flytest.controller;

import com.xdl.flytest.bean.TestCase;
import com.xdl.flytest.service.TestCaseService;
import com.xdl.flytest.util.JsonResponseMessage;
import com.xdl.flytest.util.ResponseMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import java.util.List;
import java.util.Map;

/**
 * @Auther: 80736
 * @Date: 2018/12/14 15:31
 * @Description:
 */

@Controller
@RequestMapping("/test")
public class TestCaseController {


    @Autowired
    private TestCaseService testCaseService;


    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 获取所有测试用例
     * 包含testsuit interface详细信息
     * @return
     */
    @RequestMapping(value = "/testcases", method = RequestMethod.GET)
    public ModelAndView getTestCases() {
        List<TestCase> allTestCase = testCaseService.getTestCases();
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("testcases", allTestCase);
        modelAndView.setViewName("test/page-testcase");

        return modelAndView;
    }

    /**
     * 获取所有测试用例
     * 包含testsuit interface详细信息
     *
     * @return testcases json list
     */
    @RequestMapping(value = "/testcase/all", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getAllTestCases() {
        List<TestCase> allTestCases = testCaseService.getAllTestCases();
        return new JsonResponseMessage(ResponseMsg.SUCCESS)
                .addAttribute("testcases", allTestCases).returned();

    }

    /**
     * 增加测试用例
     *
     * @param testCase
     * @return
     */
    @RequestMapping(value = "/testcase", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addTestCase(@Validated TestCase testCase, BindingResult result) {

        //如果数据校验有错误
        if (result.hasErrors()) {
            JsonResponseMessage message = new JsonResponseMessage(ResponseMsg.PARAMETER_ERROR);
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                message.addAttribute(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return message.returned();
        }

        testCaseService.addTestCase(testCase);
        return new JsonResponseMessage(ResponseMsg.SUCCESS).returned();
    }

    /**
     * 根据用例id获取用例信息
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/testcase/{id}", method = RequestMethod.GET)
    public Map<String, Object> getTestCaseById(@PathVariable("id") Integer id) {
        TestCase testcase = testCaseService.getTestCaseById(id);

        return new JsonResponseMessage(ResponseMsg.SUCCESS).addAttribute("testcase", testcase).returned();
    }

    /**
     * 更新用例信息
     *
     * @param testCase
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/testcase", method = RequestMethod.PUT)
    public Map<String, Object> updateTestCase(@Validated TestCase testCase, BindingResult result) throws UnsupportedEncodingException {
        JsonResponseMessage message = new JsonResponseMessage();
        if (result.hasErrors()) {
            message.setResponseMsg(ResponseMsg.PARAMETER_ERROR);
            message.addAttribute("error", result.getFieldError().getDefaultMessage());
            return message.returned();
        }

        testCaseService.updateTestCase(testCase);
        logger.info(">>>>>>>>>更新测试用例成功>>>>>>>>>");
        return new JsonResponseMessage(ResponseMsg.SUCCESS).returned();
    }

    /**
     * 根据id批量删除用例
     *
     * @param ids
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/testcase/{ids}", method = RequestMethod.DELETE)
    public Map<String, Object> deleteTestCase(@PathVariable("ids") String ids) {
        if (ids.contains(":")) {
            // 批量删除
            String[] idList = ids.split(":");
            testCaseService.deleteTestCases(idList);
            logger.debug(">>>>>>>>>>>>>>>>>>>>>批量删除用例结束");
        } else {
            testCaseService.deleteTestCase(Integer.parseInt(ids));
            logger.debug("删除测试用例：" + ids);
        }
        return new JsonResponseMessage(ResponseMsg.SUCCESS).returned();
    }


    @GetMapping("/testcase/run")
    @ResponseBody
    public Map<String, Object> runTestCase(@RequestParam("id") Integer testCaseId) {
        try {
            boolean result = testCaseService.runTestCaseById(testCaseId);
            if (result) {
                return new JsonResponseMessage(ResponseMsg.SUCCESS).returned();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new JsonResponseMessage(ResponseMsg.ERROR).returned();
    }

    @GetMapping("/testcase/link")
    @ResponseBody
    public Map<String, Object> linkTestSuit(@RequestParam("cid") String cid, @RequestParam("sid") String sid) {
        boolean result = testCaseService.linkTestCaseToTestSuit(cid, sid);
        if (result) {
            return new JsonResponseMessage(ResponseMsg.SUCCESS).returned();
        }

        return new JsonResponseMessage(ResponseMsg.PARAMETER_ERROR).returned();

    }




}
